package com.mornd.gulimall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mornd.gulimall.ware.entity.Purchase;
import com.mornd.gulimall.ware.entity.PurchaseDetail;
import com.mornd.gulimall.ware.entity.WareInfo;
import com.mornd.gulimall.ware.mapper.PurchaseDetailMapper;
import com.mornd.gulimall.ware.service.IPurchaseDetailService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mornd.gulimall.ware.service.IPurchaseService;
import com.mornd.gulimall.ware.service.IWareInfoService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import static com.mornd.gulimall.ware.enums.DetailStatus.ASSIGNED;
import static com.mornd.gulimall.ware.enums.DetailStatus.NEW;
import static com.mornd.gulimall.common.core.utils.BigDecimals.setScale;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mornd
 * @since 2023-07-29
 */
@Service
public class PurchaseDetailServiceImpl extends ServiceImpl<PurchaseDetailMapper, PurchaseDetail> implements IPurchaseDetailService {
    @Resource
    private IWareInfoService wareInfoService;
    @Resource
    private IPurchaseService purchaseService;

    @Override
    public IPage<PurchaseDetail> list(PurchaseDetail detail) {
        IPage<PurchaseDetail> page = new Page<>(detail.validPageNum(), detail.validPageSize());

        LambdaQueryWrapper<PurchaseDetail> qw = Wrappers.<PurchaseDetail>lambdaQuery()
                .eq(detail.getWareId() != null, PurchaseDetail::getWareId, detail.getWareId())
                .eq(detail.getStatus() != null, PurchaseDetail::getStatus, detail.getStatus());

        if (StringUtils.hasText(detail.getKey())) {
            qw.and(wrapper -> {
                // 精准匹配
                wrapper.eq(PurchaseDetail::getId, detail.getKey())
                        .or().eq(PurchaseDetail::getPurchaseId, detail.getKey());
            });
        }

        super.page(page, qw);

        for (PurchaseDetail record : page.getRecords()) {
            if (record.getWareId() != null) {
                WareInfo ware = wareInfoService.getById(record.getWareId());
                if (ware != null) {
                    record.setWareName(ware.getName());
                }
            }
        }

        return page;
    }

    @Override
    public boolean save(PurchaseDetail detail) {
        detail.setId(null);
        if (detail.getPurchaseId() == null) {
            detail.setStatus(NEW.ordinal());
        } else {
            detail.setStatus(ASSIGNED.ordinal());
        }

        BigDecimal price = setScale(detail.getSkuPrice());
        //保留两位小数，直接截取，比如1.126 会截取为 1.12
        detail.setSkuPrice(price);

        return super.save(detail);
    }

    @Override
    public boolean updateById(PurchaseDetail detail) {
        if (detail.getPurchaseId() == null) {
            detail.setStatus(NEW.ordinal());
        } else {
            detail.setStatus(ASSIGNED.ordinal());
        }
        BigDecimal price = setScale(detail.getSkuPrice());
        detail.setSkuPrice(price);
        return super.updateById(detail);
    }

    /**
     * 合并整单
     *
     * @param purchaseId
     * @param detailIds
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long merge(Long purchaseId, Long[] detailIds) {
        if (purchaseId == 0) {
            // 不存在订单就新建
            Purchase purchase = new Purchase();
            purchase.setPriority(0);
            purchaseService.save(purchase);
            purchaseId = purchase.getId();
        }

        List<PurchaseDetail> updates = new ArrayList<>();

        for (Long detailId : detailIds) {
            PurchaseDetail dbDetail = super.getById(detailId);
            // 状态为0或者1的才可以合并
            if (dbDetail == null || (!dbDetail.getStatus().equals(NEW.ordinal())
                    && !dbDetail.getStatus().equals(ASSIGNED.ordinal()))) {
                continue;
            }

            PurchaseDetail detail = new PurchaseDetail();
            detail.setId(detailId);
            detail.setPurchaseId(purchaseId);
            //  已分配
            detail.setStatus(ASSIGNED.ordinal());
            updates.add(detail);
        }

        // 批量修改
        super.updateBatchById(updates);

        // 更新日期
        purchaseService.update(Wrappers.<Purchase>lambdaUpdate()
                .set(Purchase::getUpdateTime, LocalDateTime.now())
                .eq(Purchase::getId, purchaseId));

        return purchaseId;
    }
}
